package com.cuit.mimall.controller.backend;

import com.cuit.mimall.common.R;
import com.cuit.mimall.entity.Product;
import com.cuit.mimall.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @author TeaWu
 * @folder 后台/商品
 */
@RestController("backendProductController")
@RequestMapping("/api/v1/backend/product")
public class ProductController {
    private final IProductService productService;

    @Autowired
    public ProductController(IProductService productService) {
        this.productService = productService;
    }

    /**
     * 分页查询商品列表
     *
     * @param pageNumber 页码
     * @param pageSize   每页数量
     */
    @GetMapping("/getAll")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> getAll(@RequestParam(defaultValue = "1") Integer pageNumber,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        return productService.getAll(pageNumber, pageSize);
    }

    /**
     * 添加商品
     *
     * @param product 商品信息
     */
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> add(@RequestBody Product product) {
        return productService.add(product);
    }

    /**
     * 修改商品
     *
     * @param product 商品信息
     * @return R<?> 修改结果
     */
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> update(@RequestBody Product product) {
        return productService.update(product);
    }

    /**
     * 删除商品
     *
     * @param ids 商品ids
     * @return R<?> 删除结果
     */
    @DeleteMapping("/delete")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> delete(@RequestBody Integer[] ids) {
        return productService.delete(ids);
    }

    /**
     * 根据商品ID获取商品信息
     *
     * @param id 商品ID
     * @return R<?> 商品信息
     */
    @GetMapping("/getById")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> getById(@RequestParam Integer id) {
        return R.ok(productService.getById(id));
    }
}
